package cn.flying.cloud.base.core.filter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.flying.cloud.base.core.filter.wrapper.XssHttpServletRequestWrapper;

/**
 * Xss攻击防范 Filter 过滤器，拦截请求转换为新的请求
 *
 * @author: admin
 * @date: 2023年06月15日 22:37
 * @version: 1.0
 */
public class XssFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(XssFilter.class);

    /**
     * 初始化方法
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("----XSS攻击防范过滤Filter处理开始-----");
    }

    /**
     * 过滤方法
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            String uri = ((HttpServletRequest) request).getRequestURI();
            logger.info("XssFilter拦截处理，访问请求uri：【{}】", uri);
        }
        String contentType = request.getContentType();
        //判断请求类型，文件类型特殊处理
        if (contentType != null && contentType.startsWith("multipart/")) {
            //文件上传类型
            chain.doFilter(request, response);
        } else if (request instanceof HttpServletRequest) {
            HttpServletRequest servletRequest = (HttpServletRequest) request;
            chain.doFilter(new XssHttpServletRequestWrapper(servletRequest), response);
        } else {
            chain.doFilter(request, response);
        }
    }
}